package com.yinhe.music.yhmusic.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.text.TextUtils;

import com.yinhe.music.common.utils.ImageUtils;
import com.yinhe.music.common.utils.Md5Utils;
import com.yinhe.music.common.utils.ScreenUtils;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.AppCache;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Johnson on 2018/1/4.
 */

public class PlayingCoverLoader {

    private static final String KEY_NULL = "null";

    private static PlayingCoverLoader g_instance = null;

    private Context mContext;
    /**
     * 高斯模糊图缓存，用于播放页背景
     */
    private LruCache<String, Bitmap> mBlurCache;
    /**
     * 圆形图缓存，用于播放页CD
     */
    private LruCache<String, Bitmap> mRoundCache;

    private String mCacheDir = "";

    private static int COVER_TYPE = 1;
    private static int BLUR_TYPE = 2;

    private Bitmap mDefaultConverImage = null;
    public synchronized static PlayingCoverLoader getInstance() {
        if (g_instance == null) {
            g_instance = new PlayingCoverLoader();
        }

        return g_instance;
    }

    public void initCacheDir(Context context) {
        mContext = context;
        File file = mContext.getFilesDir();
        if (file != null) {
            mCacheDir = file.getAbsolutePath() + "/coverCache";
            File cache = new File(mCacheDir);
            if (!cache.exists()) {
                cache.mkdir();
            }
        }
    }

    public void clearCache() {
        File cacheDir = new File(mCacheDir);
        if (cacheDir.isDirectory()) {
            File[] files = cacheDir.listFiles();
            for (File file : files) {
                file.delete();
            }
        }
        mBlurCache.evictAll();
        mRoundCache.evictAll();
    }

    public PlayingCoverLoader() {
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        // 缓存大小为当前进程可用内存的1/8
        int cacheSize = maxMemory / 8;
        mBlurCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount() / 1024;
            }
        };
        mRoundCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getByteCount() / 1024;
            }
        };
    }

    public void setRoundImage(String uri, Bitmap aBitmap) {
        if (TextUtils.isEmpty(uri) || aBitmap == null) {
            return;
        }

        mRoundCache.put(uri, aBitmap);
        saveBitmapFile(aBitmap, uri, COVER_TYPE);
    }

    public Bitmap getDefaultRoundImage() {
        if (mDefaultConverImage == null) {
            mDefaultConverImage = BitmapFactory.decodeResource(AppCache.getContext().getResources(), R.drawable.play_page_default_cover);
            mDefaultConverImage = ImageUtils.resizeImage(mDefaultConverImage, ScreenUtils.getScreenWidth() / 2, ScreenUtils.getScreenWidth() / 2);
            mDefaultConverImage = ImageUtils.createCircleImage(mDefaultConverImage);
        }
        return mDefaultConverImage;
    }


    public Bitmap getRoundImage(String uri) {
        if (TextUtils.isEmpty(uri)) {
            return null;
        }
        Bitmap bitmap = mRoundCache.get(uri);
        if (bitmap == null) {
            File file = getFile(uri, COVER_TYPE);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                if (bitmap != null) {
                    bitmap = ImageUtils.createCircleImage(bitmap);
                    if (bitmap != null) {
                        mRoundCache.put(uri, bitmap);
                    }
                }
            }
        }
        return bitmap;
    }


    public void setBlurImage(String uri, Bitmap aBitmap) {
        if (TextUtils.isEmpty(uri) || aBitmap == null) {
            return;
        }

        mBlurCache.put(uri, aBitmap);
        saveBitmapFile(aBitmap, uri, BLUR_TYPE);
    }

    public Bitmap getBlurImage(String uri) {
        if (TextUtils.isEmpty(uri)) {
            return null;
        }

        Bitmap bitmap = mBlurCache.get(uri);
        if (bitmap == null) {
            File file = getFile(uri, BLUR_TYPE);
            if (file != null) {
                bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                if (bitmap != null) {
                    mBlurCache.put(uri, bitmap);
                }
            }
        }
        return bitmap;
    }

    private void saveBitmapFile(final Bitmap bitmap, final String url, final int type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = getFile(url, type);
                if (file != null) {
                    try {
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private File getFile(String url, int type) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        String name = Md5Utils.getMD5(url);
        if (TextUtils.isEmpty(name)) {
            return null;
        }
        if (type == COVER_TYPE) {
            name = name + "_cover";
        } else if (type == BLUR_TYPE) {
            name = name + "_blur";
        }
        File file = new File(mCacheDir + "/" + name);
        return file;
    }


}
